// pages/cart/cart.js
const carts = require('../../utils/cart')
const { checkLogin } = require('../../utils/util')
const config = require('../../config/config')
Page({
    /**
     * 页面的初始数据
     */
    data: {
        scrollHeight: 400,
        cartData: [],
        total: 0, //总价格
        // flag: false,
        selectedGoodsNum: 0, //勾选的数量
        selectedCart: [], //勾选的商品
        selectAllStatus: false, //底部全选
    },
    // 底部选好
    async handleOk() {
        const {
            total,
            selectedGoodsNum,
            selectedCart
        } = this.data
        // 判断是否勾选了商品
        if (selectedCart.length == 0) {
            wx.showToast({
                title: '请至少勾选一件商品',
                icon: 'none'
            })
            return
        }
        //是否登录
        const userInfo = wx.getStorageSync('userInfo')
        const flag = await checkLogin(userInfo)
        if (flag == 'login') {
            wx.showModal({
                title: '确认订单',
                content: '您确认提交订单吗',
                success: res => {
                    if (res.confirm) {
                        wx.request({
                            url: `${config.server}/order/add`,
                            data: {
                                userInfo,//用户信息
                                selectedCart,//商品信息
                                total,//总金额
                                selectedGoodsNum//商品数量
                            },
                            method: 'POST',
                            success: response => {
                                if (response.data.status == 'success') {
                                    //清空购物车
                                    wx.removeStorageSync('carts')
                                    //刷新购物车
                                    this.getData()
                                    // 跳转到订单页
                                    wx.switchTab({
                                        url: '../order/order'
                                    })
                                }else{
                                    wx.showToast({
                                      title: response.data.data,
                                      icon:'error'
                                    })
                                }
                            },
                            fail: err => {
                                wx.showToast({
                                    title: '服务器异常',
                                    icon: 'error'
                                })
                            }
                        })
                    }
                }
            })
        }
    },
    // 底部全选
    selectAll() {
        let {
            selectAllStatus
        } = this.data
        selectAllStatus = !selectAllStatus
        this.setData({
            selectAllStatus
        })
        carts.setAllChosen(selectAllStatus)
        // 读取缓存 刷新页面
        this.getData()
    },
    setHeight() {
        const winHeight = wx.getSystemInfoSync().windowHeight
        // 获取手机的像素比
        const winWidth = wx.getSystemInfoSync().windowWidth
        const pr = 750 / winWidth
        const height = winHeight * pr - 110 //rpx
        this.setData({
            scrollHeight: height
        })
    },
    // 从缓存中拿数据
    getData() {
        const newData = wx.getStorageSync('carts')
        // console.log(newData);
        const cart = wx.getStorageSync('carts')
        let total = 0
        let selectedGoodsNum = 0
        let selectedCart = []
        if (cart) {
            cart.forEach(item => {
                if (item.is_chosen) {
                    total += Number(item.num) * Number(item.goods_price)
                    selectedGoodsNum += Number(item.num)
                    selectedCart.push(item)
                }
            })
        }
        this.setData({
            cartData: newData,
            total,
            selectedGoodsNum,
            selectedCart,
        })
        // 设置tabBar的徽章
        carts.setBadge()
    },
    // 购物车中点击加号加入购物车
    addcart(e) {
        // console.log(e);
        const {
            detail
        } = e.currentTarget.dataset
        detail.num = 1
        carts.add(detail)
        console.log(wx.getStorageSync('carts'));
        this.getData()
        // this.getTotal()
    },
    // 购物车中点击减号加入购物车
    minuscart(e) {
        const {
            detail
        } = e.currentTarget.dataset
        // console.log('减号');
        detail.num = -1
        carts.add(detail)
        console.log(wx.getStorageSync('carts'));
        this.getData()
        // this.getTotal()
    },
    // 复选框 勾选商品
    selectCheckout(e) {
        // console.log(e);
        const {
            index
        } = e.currentTarget.dataset
        // console.log(index);
        let {
            _id,
            is_chosen
        } = this.data.cartData[index]
        is_chosen = !is_chosen
        carts.setChosen(_id, is_chosen)
        this.getData()
        // this.getTotal()
    },
    // 获取总价格
    getTotal() {
        // console.log('获取总价格')
        const cart = wx.getStorageSync('carts')
        let num = cart.filter(item => item.is_chosen).reduce((amt, item) => {
            return amt += item.goods_price * item.num
        }, 0)
        this.setData({
            total: num
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) { },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        this.setHeight()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getData()
        // this.getTotal()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})